package com.qf.blog.system.service.impl;

import com.qf.blog.core.exception.BaseException;
import com.qf.blog.core.exception.UserNotFoundException;
import com.qf.blog.system.dto.UserToken;
import com.qf.blog.system.entity.SystemUserEntity;
import com.qf.blog.system.service.ISystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SysLoginService {

    @Autowired
    private ISystemUserService systemUserService;

    @Autowired
    private TokenService tokenService;

    // 这个方法来实现登录的操作
    public String login(String username, String password) {
        // 1.判断账号是否存在
        SystemUserEntity systemUserEntity = systemUserService.getByUsername(username);
        if (systemUserEntity == null) {
            throw new UserNotFoundException(101, "用户名不存在");
        }
        // 2.密码对比
        if (!password.equals(systemUserEntity.getPassword())) {
            throw new BaseException(101, "用户名获密码错误");
        }

        // 3.检查的账号的状态，角色等
        // 4.创建一个Token对象,基于systemUserEntity创建一个userToken对象,把用户的登录信息全部封装到userToken对象中
        UserToken userToken = tokenService.createToken(systemUserEntity);

        // 5.把token(令牌）返回给Controller
        return userToken.getToken();
    }
}
